﻿using System.Text.RegularExpressions;

namespace Tgather
{
    internal class Tool
    {
        /// <summary>获取当前时间
        /// 
        /// </summary>
        /// <param name="format">时间格式</param>
        /// <returns>时间字符串</returns>
        public static string NowTime(string format= "yyyy-MM-dd HH:mm:ss")
        { 
            return FormatDateTime(format,DateTime.Now);
        }

        /// <summary>
        /// 格式化时间
        /// </summary>
        /// <param name="format">时间格式</param>
        /// <param name="time">时间</param>
        /// <returns>时间字符串</returns>
        public static string FormatDateTime(string format, DateTime time) 
        { 
            return time.ToString(format);
        }

        /// <summary>是否是数字
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsPrivateNumber(string str)
        {
            string pattern = "(^[0-9]+$)|(^-[0-9]+$)|(^[0-9]+.[0-9]+$)|(^-[0-9]+.[0-9]+$)";

            return Regex.IsMatch(str, pattern);
        }

        /// <summary>十六进制字符串转byte
        /// 
        /// </summary>
        /// <param name="hs"></param>
        /// <returns></returns>
        public static byte[] HexStringToBytes(string hs)
        {
            string a = hs.Replace(" ", "");
            int bytelength = 0;
            if (a.Length % 2 == 0)
            {
                bytelength = a.Length / 2;
            }
            else
            {
                bytelength = a.Length / 2 + 1;
            }
            byte[] b = new byte[bytelength];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < bytelength; i++)
            {
                if (i == bytelength - 1)
                {
                    b[i] = Convert.ToByte(a.Substring(i * 2), 16);
                }
                else
                {
                    b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16);
                }
            }
            //按照指定编码将字节数组变为字符串
            return b;
        }

        /// <summary>随机数
        /// 
        /// </summary>
        /// <param name="minValue"></param>
        /// <param name="maxValue"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static double mockDouble(double minValue, double maxValue, int n)
        {
            Random ran = new Random();
            double randNum = ran.NextDouble() * (maxValue - minValue) + minValue;
            return Convert.ToDouble(randNum.ToString("f" + n));
        }
    }
}
